import { cloneDeep } from 'lodash';
import NP from 'number-precision';
import { useEffect, useRef, useState } from 'react';
import './index.less';
// import {Button} from 'antd';
import stepLoad from '@/assets/image/stepLoad.png';
// import stepLoadRotate from '@/assets/image/stepLoadRotate.gif';
import stepNOStart from '@/assets/image/stepNOStart.png';
import stepSuccess from '@/assets/image/stepSuccess.png';
const Step: React.FC<any> = ({ data, index, setProgressList }) => {
  const progressData = useRef<any>(cloneDeep(data)); //在组件里对外部数据进行响应式处理 要用useRef 不然在setTimeout自调用时数据不更新
  const [progressNum, setProgressNum] = useState<any>(0); //用来判断当前页面的进度 如果使用progressData.current.progress在显示上会有延迟
  const scrollTop = useRef(0); //篇数滑动的位置 = -总高度*进度数字
  const [showBottomTip, setShowBottomTip] = useState<boolean>(false); //下提示框的显示和隐藏

  const rotateActiveRef = useRef(null);
  const rotationSpeedRef = useRef(1); // 初始旋转速度
  //图片旋转
  const toggleRotation = (speed = 0.7, isPause = false) => {
    if (rotateActiveRef.current) {
      //速度在0.7-2的区间内 越小越快
      let currentSpeed = Math.max(0.7, Math.min(1.6, speed));
      // console.log(` ${currentSpeed}`);
      const rotateActiveElement: any = rotateActiveRef.current;
      // 获取当前旋转角度
      const currentRotation = rotationSpeedRef.current * 360;
      if (rotateActiveElement.style.animation && isPause) {
        // 如果有动画，停止动画并记录当前角度
        rotateActiveElement.style.animation = '';
        rotationSpeedRef.current = currentRotation / 360;
      } else {
        // 如果没有动画，重新启动动画
        rotateActiveElement.style.animation = `rotateAnimation ${
          currentSpeed / rotationSpeedRef.current
        }s linear infinite`;
      }
    }
  };
  const runProgress = () => {
    if (progressData.current.percent < 100 && progressData.current.run) {
      //运行一次 新的剩余时间 = 旧的剩余未完成的时间 减掉 定时器间隔时间
      let newRemainingTime = progressData.current.remainingTime - progressData.current.intervalTime;
      //当前执行剩余的次数 = 剩余未完成的时间 除以 定时器间隔
      let cishu = Number(
        (progressData.current.remainingTime / progressData.current.intervalTime).toFixed(0),
      );
      //本次要增加的进度 = 剩余进度 除以 次数
      //例如 剩余时间10秒 除以 频率1秒1次 = 10 次数 然后剩余进度100 / 10次 = 要增加10%的进度
      let addPercent = Number((progressData.current.remainingPercent / cishu).toFixed(2));
      //图片旋转速度
      toggleRotation(Number((2 / addPercent).toFixed(2)));
      //当前进度 = 旧进度+本次要增加的进度
      let oldPercent = cloneDeep(progressData.current.percent);
      //高精度计算
      let newPercent = NP.plus(oldPercent, addPercent);
      //新的剩余进度 = 旧的剩余进度 - 本次要增加的进度
      let newRemainingPercent = progressData.current.remainingPercent - addPercent;
      setProgressList((prev: any) => {
        const updatedList = prev.map((item: any, i: number) => {
          if (i === index) {
            return {
              ...item,
              percent: newPercent > 100 ? 100 : newPercent,
              remainingPercent: Number(
                (newRemainingPercent < 0 ? 0 : newRemainingPercent).toFixed(2),
              ),
              remainingTime: newRemainingTime < 0 ? 0 : newRemainingTime,
              intervalTime: progressData.current.intervalTime,
            };
          }
          return item;
        });
        return updatedList;
      });
      //递归调用
      setTimeout(() => {
        runProgress();
      }, progressData.current.intervalTime);
    }
  };
  //在外部数据更新的时候 同步组件里的数据
  useEffect(() => {
    progressData.current = cloneDeep(data);
    setProgressNum(data.percent);
    //计算篇数的滚动位置
    let top: any = 0;
    if (index === 0 || index === 1) {
      top = (-20 * (data.expected - 1) * data.percent) / 100;
    } else {
      top = (-20 * (data.select - 1) * data.percent) / 100;
    }
    scrollTop.current = top;
  }, [data]);
  //检测运行
  useEffect(() => {
    if (data.run) {
      runProgress();
    }
  }, [data.run]);
  useEffect(() => {
    if ((progressNum > 0 && progressNum < 100) || (index === 2 && progressNum === 100)) {
      setShowBottomTip(true);
    } else {
      // 如果条件不成立，延迟一段时间后隐藏
      setTimeout(() => {
        setShowBottomTip(false);
      }, 300);
    }
  }, [progressNum, index]);

  return (
    <div className="stepBox">
      <div className="stepStateBox">
        {/* <Button onClick={()=>{toggleRotation(4,false)}}>开始</Button>
      <Button onClick={()=>{toggleRotation(0.7,false)}}>开始0.5</Button>
      <img ref={rotateActiveRef}  src={stepLoad} alt="" /> */}
        <div className="stepState">
          {progressData.current.percent === 0 ? (
            <img src={stepNOStart} alt="" />
          ) : progressData.current.percent < 100 ? (
            <span>
              <img ref={rotateActiveRef} src={stepLoad} alt="" />{' '}
            </span>
          ) : (
            // (<img src={stepLoadRotate} alt="" />) :
            <img src={stepSuccess} alt="" />
          )}
        </div>
        {progressData.current.showLin ? (
          <div className="stepLine">
            <div
              className="progressBar"
              style={{ width: `${progressData.current.percent}%` }}
            ></div>
          </div>
        ) : (
          <></>
        )}
      </div>
      <div className="stepTipBox">
        <div className="stepTip1">
          {progressNum === 0 ? (
            <>{progressData.current.topTip[0] || ''}</>
          ) : progressNum < 100 ? (
            <>{progressData.current.topTip[1] || ''}</>
          ) : (
            <>{progressData.current.topTip[2] || ''}</>
          )}
        </div>
        <div className="stepTip2">
          {showBottomTip ? (
            <div className="stepTip2">
              {progressData.current.bottomTip[0]}
              <div className="scrollNumWrap">
                <div className="scrollNumBox" style={{ top: scrollTop.current }}>
                  {index === 0 || index === 1
                    ? progressData.current.expected &&
                      [...Array(progressData.current.expected || 0).keys()].map(
                        (item: any, idx: number) => (
                          <span className="scrollNum" key={idx}>
                            {item + 1}
                          </span>
                        ),
                      )
                    : progressData.current.select &&
                      [...Array(progressData.current.select || 0).keys()].map(
                        (item: any, idx: number) => (
                          <span className="scrollNum" key={idx}>
                            {item + 1}
                          </span>
                        ),
                      )}
                </div>
              </div>
              {progressData.current.bottomTip[1]}
            </div>
          ) : (
            <></>
          )}
          {/* <div className='stepTip2'>
        已生成 
        <div className='scrollNumWrap'>
          <div className='scrollNumBox' style={{top:scrollTop.current}}>
            { index === 0 || index === 1 ? 
              progressData.current.expected && [...Array(progressData.current.expected || 0).keys()].map((item:any, idx:number) => (
                <span className='scrollNum' key={idx}>
                  {item+1}
                </span>
              )) : 
              progressData.current.select && [...Array(progressData.current.select || 0).keys()].map((item:any, idx:number) => (
                <span className='scrollNum' key={idx}>
                  {item+1}
                </span>
              ))
            }
          </div>
        </div>
        篇
        </div> */}
        </div>
      </div>
    </div>
  );
};

export default Step;
